package com.stephen.redisdemo.handler;

import com.stephen.redisdemo.entity.enums.ResultEnum;
import com.stephen.redisdemo.entity.vo.CommonResponse;
import com.stephen.redisdemo.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: stephen
 * @create: 2020-02-06 13:48
 * @description: 全局异常处理器
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 自定义异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public CommonResponse businessExceptionHandler(Exception e, HttpServletRequest request) {
        BusinessException exception = (BusinessException) e;
        log.error("接口[{}]的[{}]方法发生异常",request.getServletPath(),request.getMethod().toLowerCase());
        log.error(e.getMessage(),e);
        return new CommonResponse(exception.getCode(),exception.getMessage(),exception.getData());
    }

    /**
     * Json解析异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseBody
    public CommonResponse exceptionHandler(HttpMessageNotReadableException e,HttpServletRequest request) {
        log.error("接口[{}]的[{}]方法发生异常",request.getServletPath(),request.getMethod().toLowerCase());
        log.error(e.getMessage(),e);
        return new CommonResponse(ResultEnum.JSON_PARSE_ERROR);
    }

    /**
     * 通用异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonResponse exceptionHandler(Exception e,HttpServletRequest request) {
        log.error("接口[{}]的[{}]方法发生异常",request.getServletPath(),request.getMethod().toLowerCase());
        log.error(e.getMessage(),e);
        return CommonResponse.error();
    }


}
